// 创建游戏面板
const gameContainer = document.querySelector(".game-container");
const tiles = [];
for (let i = 0; i < 16; i++) {
  const tile = document.createElement("div");
  tile.classList.add("game-tile");
  tiles.push(tile);
  gameContainer.appendChild(tile);
}
// 初始化游戏数据
let board = Array(16).fill(0);
function generateRandomTile() {
  const emptyTiles = board.reduce((acc, curr, index) => {
    if (curr === 0) {
      acc.push(index);
    }
    return acc;
  }, []);
  console.log({ emptyTiles });
  if (emptyTiles.length === 0) {
    return false;
  }
  const randomIndex = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];

  // 随机生成2或4
  board[randomIndex] = Math.random() > 0.5 ? 2 : 4;
  return true; // 成功生成新方块
}
function updateBoard() {
  for (let i = 0; i < 16; i++) {
    tiles[i].innerText = board[i] === 0 ? "" : board[i];
    tiles[i].className = `game-tile tile-${board[i]}`;
  }
}
function moveLeft() {
  let hasChanged = false;
  for (let i = 0; i < 4; i++) {
    const row = board.slice(i * 4, (i + 1) * 4);

    // 合并相同的方块
    for (let j = row.length - 1; j > 0; j--) {
      if (row[j] === row[j - 1]) {
        row[j] *= 2;
        row[j - 1] = 0;
        hasChanged = true;
      }
    }
    // 移动方块
    for (let j = row.length - 1; j > 0; j--) {
      if (row[j - 1] === 0) {
        row[j - 1] = row[j];
        row[j] = 0;
        hasChanged = true;
      }
    }
    board.splice(i * 4, 4, ...row);
  }
  return hasChanged;
}
function moveRight() {
  let hasChanged = false;
  for (let i = 0; i < 4; i++) {
    const row = board.slice(i * 4, (i + 1) * 4);

    // 合并相同的方块
    for (let j = 0; j < row.length - 1; j++) {
      if (row[j] === row[j + 1]) {
        row[j] *= 2;
        row[j + 1] = 0;
        hasChanged = true;
      }
    }
    // 移动方块
    for (let j = 0; j < row.length - 1; j++) {
      if (row[j + 1] === 0) {
        row[j + 1] = row[j];
        row[j] = 0;
        hasChanged = true;
      }
    }
    board.splice(i * 4, 4, ...row);
  }
  return hasChanged;
}
function moveUp() {
  let hasChanged = false;
  for (let i = 0; i < 4; i++) {
    const column = [board[i], board[i + 4], board[i + 8], board[i + 12]];

    // 合并相同的方块
    for (let j = column.length - 1; j > 0; j--) {
      if (column[j] === column[j - 1]) {
        column[j] *= 2;
        column[j - 1] = 0;
        hasChanged = true;
      }
    }
    // 移动方块
    for (let j = column.length - 1; j > 0; j--) {
      if (column[j - 1] === 0) {
        column[j - 1] = column[j];
        column[j] = 0;
        hasChanged = true;
      }
    }
    board[i] = column[0];
    board[i + 4] = column[1];
    board[i + 8] = column[2];
    board[i + 12] = column[3];
  }
  return hasChanged;
}
function moveDown() {
  let hasChanged = false;
  for (let i = 0; i < 4; i++) {
    const column = [board[i], board[i + 4], board[i + 8], board[i + 12]];

    // 合并相同的方块
    for (let j = 0; j < column.length - 1; j++) {
      if (column[j] === column[j + 1]) {
        column[j] *= 2;
        column[j + 1] = 0;
        hasChanged = true;
      }
    }
    // 移动方块
    for (let j = 0; j < column.length - 1; j++) {
      if (column[j + 1] === 0) {
        column[j + 1] = column[j];
        column[j] = 0;
        hasChanged = true;
      }
    }
    board[i] = column[0];
    board[i + 4] = column[1];
    board[i + 8] = column[2];
    board[i + 12] = column[3];
  }
  return hasChanged;
}
function handleKeyDown(event) {
  let hasChanged = false;
  switch (event.key) {
    case "ArrowLeft":
      hasChanged = moveLeft();
      break;
    case "ArrowRight":
      hasChanged = moveRight();
      break;
    case "ArrowUp":
      hasChanged = moveUp();
      break;
    case "ArrowDown":
      hasChanged = moveDown();
      break;
  }
  if (hasChanged) {
    generateRandomTile();
    updateBoard();
    updateSumOnRestartBox();
  } else {
    alert("结束了,点击重开吧");
    restartGame();
  }
}
// 初始化游戏
generateRandomTile();
generateRandomTile();
updateBoard();
// 监听键盘事件
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("DOMContentLoaded", function () {
  document.getElementById("upButton").addEventListener("click", function () {
    const mEvent = { key: "ArrowUp" };
    handleKeyDown(mEvent);
  });

  document.getElementById("downButton").addEventListener("click", function () {
    const mEvent = { key: "ArrowDown" };
    handleKeyDown(mEvent);
  });

  document.getElementById("leftButton").addEventListener("click", function () {
    const mEvent = { key: "ArrowLeft" };
    handleKeyDown(mEvent);
  });

  document.getElementById("rightButton").addEventListener("click", function () {
    const mEvent = { key: "ArrowRight" };
    handleKeyDown(mEvent);
  });
});

// 将board数组的总和映射到#restart的盒子上
function updateSumOnRestartBox() {
  let sum = 0;
  for (let i = 0; i < board.length; i++) {
    sum += board[i];
  }
  document.getElementById("restart").innerText = "得分: " + sum;
}

function restartGame() {
  board = Array(16).fill(0);
  generateRandomTile();
  generateRandomTile();
  updateBoard();
  updateSumOnRestartBox();
}
